package com.thirdgroup.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Objects;

/**
 * @BelongsProject: login_test
 * @BelongsPackage: com.zys.utils
 * @Author: ZYS
 * @CreateTime: 2024-04-25  09:50
 * @Description: TODO
 */
public class MD5Util {

    static MessageDigest messageDigest = null;
    static final int SALT_LENGTH = 12;

    static {
        try {
            messageDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    private MD5Util() {
        throw new AssertionError("No MD5Util instances for you!");
    }

    public static String encrypt(String str) {
        Objects.requireNonNull(str);

        byte[] salt = new byte[SALT_LENGTH];
        new SecureRandom().nextBytes(salt);

        messageDigest.update(salt);
        messageDigest.update(str.getBytes());

        byte[] digest = messageDigest.digest();

        byte[] result = new byte[digest.length + SALT_LENGTH];

        System.arraycopy(salt, 0, result, 0, SALT_LENGTH);
        System.arraycopy(digest, 0, result, SALT_LENGTH, digest.length);

        return Base64.getEncoder().encodeToString(result);

    }

    public static boolean check(String str, String encryptedStr) {
        Objects.requireNonNull(str);
        Objects.requireNonNull(encryptedStr);

        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedStr);
        byte[] salt = new byte[SALT_LENGTH];
        byte[] digest = new byte[encryptedBytes.length - SALT_LENGTH];

        System.arraycopy(encryptedBytes, 0, salt, 0, SALT_LENGTH);
        System.arraycopy(encryptedBytes, SALT_LENGTH, digest, 0, encryptedBytes.length - SALT_LENGTH);

        messageDigest.update(salt);
        messageDigest.update(str.getBytes());

        byte[] result = messageDigest.digest();

        return MessageDigest.isEqual(result, digest);
    }
//测试
    public static void main(String[] args) {
        System.out.println("encrypt(\"123456\") = " + encrypt("123456"));
        System.out.println("encrypt(\"123456\") = " + encrypt("123456"));
        System.out.println("encrypt(\"123456\") = " + encrypt("123456"));
        //encrypt("123456") = iMGtYMuF3mfQy5EPB8RsMG2cshRKEGoJTi6phQ==
        //encrypt("123456") = B+eGk/qacbEopmLslxD8obIaNOTBycbA77hMVw==

        System.out.println("check(\"123456\", \"encrypt(\"123456\")\") = " + check("123456", "B+eGk/qacbEopmLslxD8obIaNOTBycbA77hMVw=="));
        System.out.println("check(\"123456\", \"encrypt(\"123456\")\") = " + check("123456", "4DIUMeLWvZW70QFMcsiRjtq368hRquGYKcakXg=="));
        System.out.println("check(\"123456\", \"encrypt(\"123456\")\") = " + check("123456", "zvHl8ZOi2fKTZJlj/AWc1UZ5vGk0fi1Xv6E6Qg=="));
    }

}
